package controller

import (
	"context"
	v1 "gen-code-v2/api/v1"
	"gen-code-v2/internal/model"
	"gen-code-v2/internal/service"
	"github.com/gogf/gf/v2/util/gconv"
)

var (
	Database = cDatabase{}
)

type cDatabase struct{}

func (c *cDatabase) PageList(ctx context.Context, req *v1.DBPageListReq) (res *v1.DBPageListRes, err error) {
	total, list, err := service.Database().PageList(ctx, model.GenDatabaseReq{
		PageReq: req.PageReq,
		Group:   req.Group,
		Name:    req.Name,
	})
	if err != nil {
		return nil, err
	}
	res = &v1.DBPageListRes{
		Total: total,
		Rows:  list,
	}
	return
}

func (c *cDatabase) List(ctx context.Context, req *v1.DBListReq) (res *v1.DBListRes, err error) {
	list, err := service.Database().List(ctx, req.Group, req.Name)
	if err != nil {
		return nil, err
	}
	res = &v1.DBListRes{
		Rows: list,
	}
	return
}

func (c *cDatabase) Add(ctx context.Context, req *v1.DBAddReq) (res *v1.EmptyRes, err error) {
	in := new(model.DatabaseAddReq)
	err = gconv.Struct(req, in)
	if err != nil {
		return nil, err
	}
	err = service.Database().Add(ctx, *in)
	return
}

func (c *cDatabase) Delete(ctx context.Context, req *v1.DBDelReq) (res *v1.EmptyRes, err error) {
	err = service.Database().Delete(ctx, req.Ids)
	return
}
